package cn.com.http.httpmessage;

import cn.com.http.httpheader.HttpHeader;
import cn.com.http.httpheader.HttpHeaderList;
import cn.com.http.httpheader.HttpTitle;

public abstract class HttpMessage {

	String SPACE = " ";
	/** The colon character string. **/
	String COLON = ":";
	/** The newline string. **/
	String NEW_LINE = "\r\n";

	private HttpHeaderList headerList = new HttpHeaderList();

	private HttpTitle title1 = newHttpTitle1();

	private HttpTitle title2 = newHttpTitle2();

	private HttpTitle title3 = newHttpTitle3();

	protected abstract HttpTitle newHttpTitle1();

	protected abstract HttpTitle newHttpTitle2();

	protected abstract HttpTitle newHttpTitle3();

	protected final HttpTitle getTitle1() {
		return title1;
	}

	protected final HttpTitle getTitle2() {
		return title2;
	}

	protected final HttpTitle getTitle3() {
		return title3;
	}

	public final HttpHeaderList getHeaderList() {
		return headerList;
	}

	public final void addHttpHeader(String name, Object value) {
		HttpHeader httpHeader = new HttpHeader(name, value);
		getHeaderList().addHeader(httpHeader);
	}

	private HttpContent httpContent = new HttpContent();

	public HttpContent getContent() {
		return httpContent;
	}

	public String toString() {
		return toString(true);
	}

	public String toString(boolean includeContent) {
		StringBuilder message = new StringBuilder();
		message.append(toStringTitle());
		message.append(toStringHeader());
		if (includeContent)
			message.append(getContent());
		return message.toString();
	}

	private Object toStringHeader() {
		StringBuilder headers = new StringBuilder();
		for (int i = 0; i < getHeaderList().getSize(); i++) {
			HttpHeader header = getHeaderList().getHeader(i);
			headers.append(header.getName());
			headers.append(COLON);
			headers.append(SPACE);
			headers.append(header.getValue());
			headers.append(NEW_LINE);
		}
		headers.append(NEW_LINE);
		return headers.toString();
	}

	private Object toStringTitle() {
		StringBuilder title = new StringBuilder();
		title.append(getTitle1());
		title.append(SPACE);
		title.append(getTitle2());
		title.append(SPACE);
		title.append(getTitle3());
		title.append(NEW_LINE);
		return title.toString();
	}
}
